import { Controller, Get, Post, Body, Patch, Param, Delete, Query, BadRequestException, UseFilters } from '@nestjs/common';
import { MessageBoardService } from './message-board.service';
import { CreateleaveAMessageDto, MessageRo } from './dto/message-board.dto';
import { UpdateMessageBoardDto } from './dto/update-message-board.dto';
import { ApiBody, ApiOperation, ApiQuery, ApiTags } from '@nestjs/swagger';
import { UserService } from 'src/user/user.service';
import {isNil,isEmpty,clone} from 'ramda'
import { HttpExceptionFilter } from 'src/core/filter/http-exception.filter';
import { User } from 'src/user/entities/user.entity';

@ApiTags('留言板')
@Controller('messageboard')
export class MessageBoardController {
  constructor(private readonly messageBoardService: MessageBoardService,private readonly userService:UserService) {}

  @Post('createleaveAMessage')
  @ApiQuery({
    description: '创建留言',
    type: CreateleaveAMessageDto,
  })
  @ApiBody({ description: '创建留言', type: CreateleaveAMessageDto })
  @ApiOperation({ summary: '创建留言' , operationId: 'createleaveAMessage' })
  @UseFilters(new HttpExceptionFilter())
  async create(@Body() body: CreateleaveAMessageDto){
    const {userId,toUserId,messageBoardId} = body
    const user = await this.userService.findOne(userId)
    let toUser : User
    if(!isNil(messageBoardId)&&!isEmpty(messageBoardId)){
      const users = await this.userService.findOne(toUserId)
      toUser = users
    }
    return await this.messageBoardService.create(body,{user,toUser})
  }

  @Get('/query')
  async findAll(
    @Query() query,
    @Query('pageSize') pageSize: number,
    @Query('pageNum') pageNum: number,
  ): Promise<MessageRo> {
    try{
      const data = await this.messageBoardService.findAll(query);
      const fatherList = []
      const sonList =[]
      const sonListObj = {}

      for(const iterator of data.sonList){
        const item = clone(iterator)
        const userInfo = await this.userService.findOne(item.userId)
        const toUserInfo = await this.userService.findOne(item.toUserId)
        const obj = {
          ...item,
          toUserName:toUserInfo.username,
          userName:userInfo.username,
        }
        sonList.push(obj)
      
        const arr1 = sonListObj[item.parseId]?sonListObj[item.parseId]:[]
        arr1.push(obj)
        arr1.sort((a, b) => a.id - b.id);
        sonListObj[item.parseId] = arr1
      }
      //遍历父评论数组
      for(const iterator of data.list){
        const item = clone(iterator)
        delete item.user
        const userInfo = await this.userService.findOne(item.userId)
        if(sonListObj[item.id]){
          const twoMessageBoard=[...sonListObj[item.id]]
          item.twoMessageBoard = twoMessageBoard
        }else{
          item.twoMessageBoard = []
        }
        fatherList.push({...item,userName:userInfo.username})
      }
      // for(const fatherItem of fatherList){
      //   if(sonListObj[fatherItem.id]){
      //     const twoMessageBoard=[...sonListObj[fatherItem.id]]
      //     fatherItem.twoMessageBoard = twoMessageBoard
      //   }else{
      //     fatherItem.twoMessageBoard = []
      //   }
      // }
      data.list = fatherList
      data.count = fatherList.length
      return {list:data.list,count:data.count}
    }catch(error){
      throw new BadRequestException(error.message);
    }
  }

}

